package com.ihealthway.all.groupbuy.modules;

import com.ihealthway.all.commons.Constants;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.View;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.view.RawView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Special module use for anywhere no only back or front.
 * @author 凡梦星尘(elkan1788@gmail.com)
 */
@At("/commons")
@IocBean
public class CommonsModule {

    private final static Log logger = Logs.get();

    @Inject("refer:conf")
    private PropertiesProxy props;

    /**
     * Show upload image
     * @param type      choose goods image or shop ad image
     * @param fileName  which image to show on
     * @return  RAW type view
     */
    @At
    @GET
    @Ok("raw")
    public View imgView(@Param("type") String type, @Param("fileName") String fileName, HttpServletRequest req, HttpServletResponse resp) throws Throwable {
        File file = null;

        if(Strings.isNotBlank(type) && Strings.isNotBlank(fileName)) {
            String filePath = "";
            switch (type) {
                case "goods":
                    filePath = props.getTrim(Constants.UPLOAD_ATTACHMENT_SAVE_PATH)
                            + props.getTrim(Constants.GOODS_IMG_FOLDER);
                    break;
                case "ad":
                    filePath = props.getTrim(Constants.UPLOAD_ATTACHMENT_SAVE_PATH)
                            + props.getTrim(Constants.SHOP_AD_FOLDER);
                    break;
                case "um":
                    filePath = props.getTrim(Constants.UPLOAD_ATTACHMENT_SAVE_PATH)
                            + props.getTrim(Constants.UM_ATTACHMENT_IMG_FOLDER);
                    break;
                case "rwd":
                    filePath = props.getTrim(Constants.UPLOAD_ATTACHMENT_SAVE_PATH)
                            + props.getTrim(Constants.REWARD_IMG_FOLDER);
                    break;
            }

            if (Strings.isNotBlank(filePath)) {
                file = new File(filePath+fileName);
            }
        }

        String ctxType = "png";
        if (file != null) {
            int index = file.getName().lastIndexOf(".");
            ctxType = file.getName().substring(index+1);
        }

        RawView view = new RawView(ctxType);
        BufferedImage bufferImg = ImageIO.read(new FileInputStream(file));
        view.render(req, resp, bufferImg);
        return view;
    }

    @At
    @Ok("beetl:user-agent.jsp")
    public void testUserAgent(HttpServletRequest request) {
        String userAgent = request.getHeader("user-agent");
        logger.infof("UserAgent: %s", userAgent);

        Map<String, String> ua = new HashMap<>();

        Pattern pattern = Pattern.compile("iPhone\\s+OS\\s+([\\d\\_]+)|Android\\s+([\\d\\.]+)|MicroMessenger\\/([\\d\\.]+)|NetType\\/[0-9a-zA-Z+]*", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(userAgent);
        int i=0;
        while (matcher.find()) {
            switch (i) {
                case 0:
                    String os = matcher.group();
                    ua.put("os", os.split(" ")[0]);
                    break;
                case 1:
                    String ver = matcher.group();
                    ua.put("ver", ver.split("/")[1]);
                    break;
                case 2:
                    String net = matcher.group();
                    ua.put("net", net.split("/")[1]);
                    break;
            }
            i++;
        }

        logger.info(ua);
        request.setAttribute("ua", ua);
    }

}
